package com.tencent.backstage.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tencent.backstage.mapper.ChapterMapper;
import com.tencent.backstage.mapper.CourseMapper;
import com.tencent.backstage.mapper.CourseTypeMapper;
import com.tencent.backstage.mapper.VideoMapper;
import com.tencent.backstage.pojo.*;
import com.tencent.backstage.vo.CourseVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CourseService {

    @Resource
    private CourseMapper cm;

    @Resource
    private CourseTypeMapper ctm;

    @Resource
    private ChapterMapper chapterMapper;

    @Resource
    private VideoMapper videoMapper;

    public List<CourseType> getCourseType() {
        List<CourseType> list = ctm.selectAll();
        return list;
    }

    public PageInfo<Course> getCourseList(CourseVo courseVo) {
        Page<Object> page = PageHelper.startPage(courseVo.getCurrent(), courseVo.getPageSize());
        List<Course> list = new ArrayList<>();
        if(!StringUtils.isEmpty(courseVo.getTitle())){
            Example example = new Example(Course.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andLike("title","%"+courseVo.getTitle()+"%");
            list = cm.selectByExample(example);
        }else{
            list = cm.selectAll();
        }
        PageInfo<Course> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    public List<ChapterAndVideo> getCourseChapterAndVideoList(Course course) {
        ArrayList<ChapterAndVideo> chapterAndVideoList = new ArrayList<>();
        Example example = new Example(Chapter.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("courseId",course.getId());
        List<Chapter> list = chapterMapper.selectByExample(example);
        for (Chapter chapter : list) {
            Example example1 = new Example(Video.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("chapterId",chapter.getId()+"");
            List<Video> videoList = videoMapper.selectByExample(example1);
            ChapterAndVideo chapterAndVideo = new ChapterAndVideo(chapter, videoList);
            chapterAndVideoList.add(chapterAndVideo);
        }
        return chapterAndVideoList;
    }
}
